package cn.sibu.disalllowtouchintercept.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import cn.sibu.disalllowtouchintercept.R;

public class ExchangeActivity extends AppCompatActivity {

    //本应用程序唯一的UUID
    private  static final UUID MY_UUID = UUID.fromString("39ed4952-aba0-11e5-bf7f-feff819cdc9f");

    //发现时用于匹配的一个更加友好的名称
    private  static final String SEARCH_NAME = "bluetooth.recipe";

    BluetoothAdapter mBtAdapter;
    BluetoothSocket  mBtSocket;
    Button listenButton, scanButton;
    EditText emailField;
    String email;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_exchange);

        //检查系统状态
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBtAdapter==null){
            Toast.makeText(this,"Bluetooth is not supported.",Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        if(!mBtAdapter.isEnabled()){
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent,REQUEST_ENABLE);
        }
        emailField  = (EditText) findViewById(R.id.emailField);
        listenButton = (Button) findViewById(R.id.listen);
        listenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //首先要确保设备是可以发现的
                if(mBtAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
                    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                    startActivityForResult(discoverableIntent,REQUEST_DISCOVERABLE);
                    return;
                }
                startListening();
            }
        });
        scanButton = (Button) findViewById(R.id.scanButton);
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBtAdapter.startDiscovery();
                setProgressBarIndeterminateVisibility(true);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //为Activity注册广播Intent
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver,filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver,filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if(mBtSocket!=null){
                mBtSocket.close();
            }
        }catch (IOException e){

        }
    }

    private static final int REQUEST_ENABLE = 1;
    private static final int REQUEST_DISCOVERABLE = 2;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){

            case REQUEST_ENABLE:
                if(resultCode != Activity.RESULT_OK){
                    Toast.makeText(this,"Bluetooth Not Enable",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            case REQUEST_DISCOVERABLE:
                if(resultCode == Activity.RESULT_CANCELED){
                    Toast.makeText(this,"Must be discoverable.",Toast.LENGTH_SHORT).show();
                }else {
                    startListening();
                }
                break;
            default:
                break;
        }
    }

    //启动服务器套接字并监听
    private void startListening(){
        AcceptTask task = new AcceptTask();
        task.equals(MY_UUID);
        setProgressBarIndeterminateVisibility(true);
    }

    //AsyncTask接受传入的连接

    private class AcceptTask extends AsyncTask<UUID,Void,BluetoothSocket>{

        @Override
        protected BluetoothSocket doInBackground(UUID... params) {
            String name = mBtAdapter.getName();
            try {
                //监听时,将发现名设置为指定的值
                mBtAdapter.setName(SEARCH_NAME);
                BluetoothServerSocket socket = mBtAdapter.listenUsingRfcommWithServiceRecord("BluetoothRecipe",params[0]);

                BluetoothSocket connected = socket.accept();
                //复位蓝牙适配器名称
                mBtAdapter.setName(name);
                return connected;
            } catch (IOException e) {
                e.printStackTrace();
                mBtAdapter.setName(name);
                return null;
            }
        }

        @Override
        protected void onPostExecute(BluetoothSocket bluetoothSocket) {
            if(bluetoothSocket==null){
                return;
            }
            email = emailField.getText().toString();
            mBtSocket = bluetoothSocket;

        }
    }

    //AysncTask接收一行数据并发送
    private class ConnectedTask extends AsyncTask<BluetoothSocket,Void,String>{

        @Override
        protected String doInBackground(BluetoothSocket... params) {
            InputStream in = null;
            OutputStream out = null;

            try {
                //发送数据
                out = params[0].getOutputStream();
                out.write(email.getBytes());

                //接收其他数据
                in = params[0].getInputStream();
                byte[] buffer = new byte[1024];
                in.read(buffer);
                //从结果创建一个空字符串
                String result = new String(buffer);
                //关闭连接
                mBtSocket.close();
                return result.trim();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(ExchangeActivity.this,result,Toast.LENGTH_SHORT).show();
            setProgressBarIndeterminateVisibility(false);
        }
    }

    //用来监听发现设备的BroadcastReceiver

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            //当找到一台设备
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                //从Intent中获得BluetoothDevice对象
                BluetoothDevice device =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(TextUtils.equals(device.getName(),SEARCH_NAME)){
                    //匹配找到的设备,连接
                    mBtAdapter.cancelDiscovery();

                    try {
                        mBtSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                        mBtSocket.connect();
                        ConnectedTask task = new ConnectedTask();
                        task.execute(mBtSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //发现完成
            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                setProgressBarIndeterminateVisibility(false);
            }
        }
    };
}
